import React, { useEffect, forwardRef, useImperativeHandle } from "react";
import sdk from 'qcloud-iotexplorer-h5-panel-sdk';
import classNames from "classnames";
import { useHistory } from "react-router-dom";
import { Toast } from 'antd-mobile';
import {
	StandardBleConnectStatus,
	useStandardBleConnector,
} from "../hooks/useStandardBleConnector";
import "./StandardBleConnector.less";
import { useState } from "react";
import { addDevData} from '../../DevicePanel/Jkcard';
import { IMGURL,forunit} from '../../utils/common';
export const StandardBleConnector = forwardRef(
  ({ deviceId, familyId }, ref) => {
    const [
			connectStatusInfo,
			isconnected, //蓝牙连接状态
			bleMessage, //蓝牙广播
      bleData,
			{      
				deviceAdapter,
				connectDevice,
				deleteDevice,
				controlDevice,
				disconnectDevice,
				controlAction,
			},
		] = useStandardBleConnector({
			deviceId,
			familyId,
		});
    useImperativeHandle(ref, () => ({
			connectStatusInfo,
			deviceAdapter,
			isconnected, //蓝牙连接状态
			bleMessage, //蓝牙广播
      bleData,
			connectDevice,
			deleteDevice,
			controlDevice,
			disconnectDevice,
		}));
    const renderLinkBtn = (status) => {
      {connectStatusInfo.status === 'connected' && (
        <div className="pdtb">
          <span className="lfbtn-dis" onClick={connectDevice}>设备已连接</span>
        </div>
      )}

      switch (status) {
        case StandardBleConnectStatus.DISCONNECTED: {
          return (
              <span className="lfbtn" onClick={connectDevice}>立即连接</span>
          );
        }
        case StandardBleConnectStatus.CONNECTING: {
          return (
            <div>
              <div className="connimg pdt fl-rc">
                <img src={IMGURL+"lf-tzc.png"} width="45px"/>
                <img src={IMGURL+"lfloading.png"} height="25px" className="pdlr"/>
                <img src={IMGURL+"lf-blt.png"} width="45px"/>
              </div>
            </div>
          );
        }

        case StandardBleConnectStatus.CONNECTED: {
          return (
              <span className="lfbtn" onClick={disconnectDevice}>断开</span>
          );
        }

        case StandardBleConnectStatus.ERROR: {
          return (
              <span className="lfbtn" onClick={connectDevice}>重试</span>
          );
        }
      }
    };
    const history = useHistory()
    // 从云端获取到的属性枚举值
    const wulist = sdk.templateMap!=undefined ? sdk.templateMap.weight_unit.define.mapping : ["KG","斤","磅"]
    const unitindex = sdk.deviceData!=undefined ?  sdk.deviceData.weight_unit : 0
    const [iweight,setiweight] = useState("0.00")
    const [iweight_unit,setiweight_unit] = useState("KG")
    let weightdata ={}
    const controDev = async (bleData,bleMessage) =>{
      console.log("controDev-jxData",bleMessage)
      let fjxdata = {
        // "battery_status":bleMessage.battery_status,
        "weight_unit":parseInt(weightdata.weight_unit),
        "weight":parseFloat(weightdata.weight),
        "body_r":parseFloat(bleMessage.body_r.toFixed(2)),
        "stable_data_flag":parseInt(bleMessage.stable_data_flag)
      }
      console.error(fjxdata)
      await sdk.controlDeviceData(fjxdata)
      await addDevData(bleMessage,bleData)
      await history.replace('/Home', bleMessage)
    }
    useEffect(() => {
      if(Object.keys(bleMessage).length > 0){
        console.log('bleMessage',bleMessage)
        if (bleMessage.weight ==NaN || bleMessage.weight ==null || bleMessage.weight < 0 || bleMessage.weight_unit ==null  || bleMessage.weight_unit ==NaN ){
          setiweight("0.0")
          setiweight_unit("KG")
        }else {
          weightdata = forunit(bleMessage.weight,bleMessage.weight_unit)
          setiweight(weightdata.weight)
          setiweight_unit(wulist[weightdata.weight_unit])
          if(bleMessage.stable_data_flag == 1 && bleMessage.weight > 0){
            controDev(bleData,bleMessage);
            console.error('稳定bleMessage：-',bleData,bleMessage);
            Toast.hide();
            // disconnectDevice()
          }
        }
      }
    }, [bleMessage])
    return (
      <div className="fl-cc">
        <div className="pdtb tc weightcon">
          <div className="weighttext tittext">
            {iweight}<span className="ttext">{iweight_unit}</span>
          </div>
          <img src={IMGURL+"ljtzc_img_scale@2x.png"} width="62%"/>
        </div>
        <div className="pdtb textcolor">请打开蓝牙<img src={IMGURL+"ljtzc_ic_bluetooth@2x.png"} width="12px"/> ，保持网络畅通，光脚站在秤上</div>
        <div className={classNames("blue-tooth-connectornew", connectStatusInfo.status)}>
          <div className="tittext tc pdtb">{connectStatusInfo.msg}</div>
        </div>
        <div className="pdtb">
          {renderLinkBtn(connectStatusInfo.status)}
        </div>
      </div>
    );
  }
);